﻿using CommonDevelop;
using CommonDevelop.Operator;
using CommonEngine;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;
using WebAdmin.Models;

namespace WebAdmin.Controllers
{
    /// <summary>
    /// 用户登录
    /// </summary>
    public class LoginController : Controller
    {
        private readonly IPathProvider pathProvider;
        /// <summary>
        /// 构造注入
        /// </summary>
        public LoginController(IPathProvider pathProvider)
        {
            this.pathProvider = pathProvider;
        }

        /// <summary>
        /// 登录跳转清空Session
        /// </summary>
        [HttpGet]
        public ActionResult Index()
        {
            OperatorProvider.Provider.EmptyCurrentData();
            return RedirectToAction("Login", "Login");
        }

        /// <summary>
        /// 验证码
        /// </summary>
        [HttpGet]
        public ActionResult LoginImg(int id)
        {
            string str = null;
            var ms = ValidateHelper.VerifyImage(ref str);
            OperatorProvider.Provider.SetCookies("VerifyCode", str, 8);
            return File(new MemoryStream(ms), "image/gif", "Login.gif");
        }

        /// <summary>
        /// 登录页
        /// </summary>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login(string returnUrl = null)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                if (Request.Path != null)
                {
                    returnUrl = Request.Path.ToString();
                    //来源页面是错误页面则不返回
                    if (!string.IsNullOrEmpty(returnUrl) && returnUrl.ToLower().Contains("error"))
                    {
                        returnUrl = string.Empty;
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(GlobalData.DomainPath))
                GlobalData.DomainPath = this.pathProvider.GetHostUri(this.Request);

            TempData["ReturnUrl"] = returnUrl;
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.Title = "系统登录";
            return View(new LoginViewModel());
        }

        /// <summary>
        /// 登录提交
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken] //访XSS攻击
        public ActionResult Login(LoginViewModel model)
        {
            string returnUrl = null;
            if (TempData["ReturnUrl"] != null)
                returnUrl = TempData["ReturnUrl"] as string;

            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(model.VerifyCode))
                    model.VerifyCode = string.Empty;

                var VCode = OperatorProvider.Provider.GetCookies("VerifyCode");
                if (string.IsNullOrWhiteSpace(VCode) || model.VerifyCode.ToLower() != VCode.ToLower())
                {
                    ModelState.AddModelError(string.Empty, "验证码错误");
                }
                else
                {
                    if (OperatorProvider.Provider.GetCurrentErrorNum() > 6)
                    {
                        ModelState.AddModelError(string.Empty, "登录失败次数过多，请先确认账号");
                    }
                    else
                    {
                        model.UIP = OperatorProvider.Provider.GetIP();
                        if (!this.User_Login(model, out string error))
                        {
                            OperatorProvider.Provider.AddCurrentErrorNum();
                            ModelState.AddModelError(string.Empty, error);
                        }
                        else
                        {
                            OperatorProvider.Provider.ClearCurrentErrorNum();
                            return RedirectToLocal(returnUrl);
                        }
                    }
                }
            }
            else
                ModelState.AddModelError(string.Empty, "登录失败");

            return View(model);
        }

        /// <summary>
        /// 登录用户
        /// </summary>
        public bool User_Login(LoginViewModel VM, out string error)
        {
            error = null;
            string name = CommonOP.Formatstr(VM.UserName);
            string pass = CommonOP.Formatstr(VM.Password);

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass))
            {
                error = "用户名及密码不能为空";
                return false;
            }

            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(pass))
            {
                error = "用户名及密码不能为空";
                return false;
            }

            //---登录操作---
            var v = OperatorProvider.Provider.CheckLogin(name, pass).Outcome(a => a);
            if (v.Errors.IsEmpty())
            {
                LogModel operateLogModel = new LogModel();
                operateLogModel.LogTitle = v.result.FullName;
                operateLogModel.LogType = LogType.Login;
                operateLogModel.LogModule = "LoginController.User_Login";
                operateLogModel.ContentJson = v.result.Token;
                operateLogModel.OperateUserId = v.result.UserId;
                operateLogModel.OperateAccount = v.result.Account;
                //日志记录
                OperatorProvider.Provider.WriteOperateLog(operateLogModel);
                return true;
            }
            else
            {
                error = v.Errors ?? "用户名或密码不正确";
                return false;
            }
        }

        /// <summary>
        /// 重定向操作
        /// </summary>
        private ActionResult RedirectToLocal(string returnUrl)
        {
            returnUrl = null;   //场景要求所有登录都指向首页
            if (string.IsNullOrEmpty(returnUrl))
                return RedirectToAction("Main", "Home");

            string[] AtctionAndControll = returnUrl.Split('/');
            if (AtctionAndControll != null && AtctionAndControll.Count() == 2)
                return RedirectToAction(AtctionAndControll[1], AtctionAndControll[0]);
            else if (AtctionAndControll.Contains("Login"))
                return RedirectToAction("Main", "Home");
            else
                return Redirect(returnUrl);
        }
    }
}
